package com.pig.openg1.data;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.util.Log;
import android.view.View;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

public class Triangle {

    private final String TAG = Triangle.class.getSimpleName();

    private int vCount;
    private FloatBuffer mVerBuffer,mColorBuffer;
    private ShortBuffer mIndexBuffer;
    private View mView;
    private int mProgram;
    private int aPosition,aColor;
    private int muMVPMatrix;

    //初始化矩阵数据
    public static float[] mProMatrix = new float[16];
    public static float[] mVMatrix = new float[16];
    public static float[] mMVPMatrix; //总变换矩阵
    public static float[] mMMatrix = new float[16]; //变化矩阵



    public Triangle(View view)
    {
        this.mView = view;
        //初始化数据
        vCount = 4;
        float UNIT_SIZE = 0.2f;
        float[] ver = new float[]{
                -4 * UNIT_SIZE ,0,0,
                0,-4 * UNIT_SIZE ,0,
                4 * UNIT_SIZE ,0,0,
                0,4* UNIT_SIZE,0,0
        };
        mVerBuffer = getFloatBuffer(ver);
        float color[] = new float[]{
                1,0,1,0,
                1,1,0,0,
                0,1,0,0,
                0,0,1,1
        };
        mColorBuffer = getFloatBuffer(color);
        short index[] = new short[]{0,1,2,1,2,3};
        mIndexBuffer = getShortBuffer(index);
        String verString = loadFormAssertFile("ver.glsl",mView.getContext());
        String fragString = loadFormAssertFile("frag.glsl",mView.getContext());
        //加载着色器程序
        mProgram = createProgram(verString,fragString);
        aPosition = GLES20.glGetAttribLocation(mProgram,"aPosition");
        aColor = GLES20.glGetAttribLocation(mProgram,"aColor");
        muMVPMatrix = GLES20.glGetUniformLocation(mProgram,"uMVPMatrix");
    }

    private ShortBuffer getShortBuffer(short[] index) {
        ByteBuffer mByteBuffer = ByteBuffer.allocateDirect(index.length * 2);
        mByteBuffer.order(ByteOrder.nativeOrder());
        ShortBuffer mShortBuffer = mByteBuffer.asShortBuffer();
        mShortBuffer.put(index);
        mShortBuffer.position(0);
        return mShortBuffer;
    }

    private int createProgram(String verString, String fragString) {
        int verTex = loadShader(GLES20.GL_VERTEX_SHADER,verString);
        if(verTex == 0 )
            return 0;
        int pixShader = loadShader(GLES20.GL_FRAGMENT_SHADER,fragString);
        if(pixShader == 0 )
            return 0;
        int program = GLES20.glCreateProgram();
        if(program != 0 )
        {
            GLES20.glAttachShader(program,verTex);
            GLES20.glAttachShader(program,pixShader);
            GLES20.glLinkProgram(program);
            int[] linkStatus = new int[1];
            GLES20.glGetProgramiv(program,GLES20.GL_LINK_STATUS,linkStatus,0);
            if(linkStatus[0] != GLES20.GL_TRUE)
            {
                Log.e(TAG,GLES20.glGetProgramInfoLog(program));
                GLES20.glDeleteProgram(program);
                program = 0;
            }
        }
        return program;
    }

    /***
     * 加载制定的shader的方法
     * @param type
     * @param verString
     * @return
     */
    private int loadShader(int type, String verString) {
        //1. 创建一个着色器
        int shader= GLES20.glCreateShader(type);
        if(shader != 0)
        {
            GLES20.glShaderSource(shader,verString);
            GLES20.glCompileShader(shader);
            int[] compiled = new int[1];
            GLES20.glGetShaderiv(shader,GLES20.GL_COMPILE_STATUS,compiled,0);
            if(compiled[0] != GLES20.GL_TRUE)
            {
                Log.e(TAG,"" + GLES20.glGetShaderInfoLog(shader));
                GLES20.glDeleteShader(shader);
                shader = 0;
            }
        }
        return shader;
    }

    private String loadFormAssertFile(String file, Context context) {

        String result = null;
        try{
            InputStream in  = context.getResources().getAssets().open(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int length = 0;
            byte[] buffer = new byte[1024];
            while ( (length = in.read(buffer))> 0 )
            {
                out.write(buffer,0,length);
            }
            in.close();
            result = out.toString();
            result = result.replaceAll("\\r\\n","\n");
            Log.i(TAG,"加载的文件： "+ result);
        }catch(Exception e)
        {
            Log.e(TAG,"加载文件异常： " + e.getMessage());
        }
        return result;
    }

    private FloatBuffer getFloatBuffer(float[] ver) {
        ByteBuffer mByteBuffer = ByteBuffer.allocateDirect( ver.length * 4 );
        mByteBuffer.order(ByteOrder.nativeOrder());
        FloatBuffer mFloatBuffer = mByteBuffer.asFloatBuffer();
        mFloatBuffer.put(ver);
        mFloatBuffer.position(0);
        return mFloatBuffer;
    }

    public static float[] getFinalMatrix(float[] space)
    {
        mMVPMatrix = new float[16];
        Matrix.multiplyMM(mMVPMatrix,0,
                mVMatrix,0,
                space,0);
        Matrix.multiplyMM(mMVPMatrix,0,
                mProMatrix,0,
                mMVPMatrix,0);
        return mMVPMatrix;
    }

    public void drawSelf()
    {
        GLES20.glUseProgram(mProgram);
        Matrix.setRotateM(mMMatrix,0,0,
                0,1,0);
        Matrix.translateM(mMMatrix,0,
                0,0,1);
        Matrix.setRotateM(mMMatrix,0,0,
                1,1,1);
        GLES20.glUniformMatrix4fv(muMVPMatrix,1,false,getFinalMatrix(mMMatrix),0);
        GLES20.glVertexAttribPointer(aPosition,3,GLES20.GL_FLOAT,false,0,mVerBuffer);
        GLES20.glVertexAttribPointer(aColor,4,GLES20.GL_FLOAT,false,0,mColorBuffer);
        GLES20.glEnableVertexAttribArray(aPosition);
        GLES20.glEnableVertexAttribArray(aColor);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN,0,vCount);
//        GLES20.glDrawElements(GLES20.GL_TRIANGLES,4,GLES20.GL_FLOAT,mIndexBuffer);
        GLES20.glDisableVertexAttribArray(aPosition);
        GLES20.glDisableVertexAttribArray(aColor);

    }

}
